#include "FilesReader.hpp"

Polygon FileReader::create_polygon_from_file(const string& filename)
{
	Polygon polygon;
    
	vector<Point> v = read_from_file(filename);

	for (vector<Point>::const_iterator it = v.begin();
		it != v.end();
		it++)
	{
		polygon.push_back(*it);
	}

	return polygon;
}

Polygon FileReader::create_polygon( const std::string& polygon_string ) 
{
    string local_polygon_string = polygon_string;

    Polygon polygon;
    std::string delimiter = " ";
    std::string token;

    size_t pos = local_polygon_string.find(delimiter);

    if (pos == std::string::npos)
    {
        throw Exception("Invalid Polygon file");
    }
    string number_of_vertices_string = local_polygon_string.substr(0, pos);
    int number_of_vertices = atoi(number_of_vertices_string.c_str());
    local_polygon_string.erase(0,pos + number_of_vertices_string.length());

    for (int i = 0; i < number_of_vertices; ++i)
    {
        pos = local_polygon_string.find(delimiter);

        if (pos == std::string::npos)
        {
            throw Exception("Invalid Polygon file");
        }
        string x_value_string = local_polygon_string.substr(0, pos);
        local_polygon_string.erase(0,pos + x_value_string.length());
        int x_value = atoi(x_value_string.c_str());

        pos = local_polygon_string.find(delimiter);

        if (pos == std::string::npos)
        {
            if (i != number_of_vertices - 1)
            {
                throw Exception("Invalid Polygon file");
            }

            int y_value = atoi(local_polygon_string.c_str());
            Point point(x_value, y_value);
            polygon.push_back(point);
            break;
        }
        string y_value_string = local_polygon_string.substr(0, pos);
        local_polygon_string.erase(0,pos + y_value_string.length());
        int y_value = atoi(y_value_string.c_str());

        Point point(x_value, y_value);
        polygon.push_back(point);
    }

    if (!polygon.is_simple())
    {
        throw Exception("Polygon is not simple!");
    }

    return polygon;
}

std::vector<Point> FileReader::create_cameras_list(const string& filename)
{
    return read_from_file(filename);
}

vector<Point> FileReader::read_from_file(string path)
{
	vector<Point> points;

    std::ifstream points_file(path.c_str());

    if (!points_file)
    {
        throw Exception("Ilegal file");
    }

    unsigned int point_count = 0;
    std::string point_count_line;
    std::getline(points_file, point_count_line);
    std::istringstream(point_count_line) >> point_count;

    std::istream_iterator< Point > input_begin( points_file );
    std::istream_iterator< Point > input_end;

    points.insert(points.begin(), input_begin, input_end);

    if (points.size() != point_count)
    {
        throw Exception("Ilegal file format");
    }

    return points;
}
